import React, {useEffect, useRef, useState} from 'react';
import {Avatar, Button, message} from "antd";
import classes from './index.module.scss'
import {ReactEmojiEditor} from "react-emotor";
import {
    CommentOutlined
} from '@ant-design/icons';
import {getToken} from "../../../../utils/token";
import LoginAlert from "../../../LoginAlert";
import {useDispatch, useSelector} from "react-redux";
import {useParams} from "react-router-dom";
import {reqReplyComment} from "../../../../api/frontDesk/frontDeskApi";
import {getCommentList} from "../../../../store/frontDesk/commentSlice";

const Comment = ({comment, level = 0, users}) => {
    const dispatch = useDispatch()
    const token = getToken()
    const emotor = useRef();
    const params = useParams()

    const [appear, setAppear] = useState(false)
    const [open, setOpen] = useState(false);
    const [replyUserName, setReplyUserName] = useState('未知用户')
    //回复按钮
    const [content, setContent] = useState('')

    const {userAllInfo} = useSelector(state => state.persistedReducer.user)

    // 组件内容改变回调函数
    const contentOnChange = (content) => {
        setContent(content)
    }


    //回复按钮
    const replyBtn = () => {
        if (token) {
            setAppear(true)
        } else {
            setOpen(!open)
        }
    }
    useEffect(() => {
        if (users && comment && level !== 0) {
            const replyUserId = parseInt(comment.user_info.split('回复')[1])
            const replyUser = users.find(user => user.id === replyUserId)
            const newReplyUserName = replyUser ? replyUser.nickname : '未知用户'
            setReplyUserName(newReplyUserName)
        }
    }, [comment.user_info, users])

    // 清空组件内容
    function clean() {
        emotor.current.clean();
    }

    // 组件获取焦点
    const publishComment = async () => {
        if (getToken()) {
            if (content !== '') {
                const result =
                    await reqReplyComment({
                            article_id: params.id,
                            user_id: userAllInfo.id,
                            content,
                            parent_comment_id: comment.id
                        }
                    )
                if (result.status === 0) {
                    const getData = () => {
                        dispatch(getCommentList(params.id))
                    }
                    getData()
                    message.success('回复成功')
                    emotor.current.clean();
                    setAppear(false)
                }
            } else {
                message.info('请不要发表空的评论')
            }
        } else {
            message.info('请先登录')
        }
    }

    return (
        <div>
            <div>
                <div className={classes.Box}>
                    <div style={{display: 'flex'}}>
                        <Avatar src={comment.user_avatar} size={55}/>
                        <div className={classes.Content}>
                            {
                                level > 0 ?
                                    <div>
                                        <span>
                                            {
                                                comment.user_info.split('回复')[0] === userAllInfo.nickname ?
                                                    '我' : comment.user_info.split('回复')[0]
                                            }
                                        </span>
                                        <span style={{color: '#aaa', padding: '0 20px'}}>回复</span>
                                        <span style={{color: 'orange'}}>
                                            {
                                                replyUserName === userAllInfo.nickname ? '我' : replyUserName
                                            }
                                        </span>
                                    </div>
                                    :
                                    comment.user_info === userAllInfo.nickname ? '我' : comment.user_info
                            }
                            <div style={{display: 'flex', alignItems: 'center'}}>
                                {
                                    comment.content
                                }
                                {
                                    appear === false ?
                                        <div onClick={() => setOpen(!open)}>
                                            <Button onClick={replyBtn} type="link">
                                                <CommentOutlined/> 回复
                                            </Button>
                                            {open && <LoginAlert open={open}/>}

                                        </div>
                                        :
                                        <Button onClick={() => setAppear(false)} type="link">
                                            <CommentOutlined/> 取消回复
                                        </Button>
                                }

                            </div>
                        </div>
                    </div>
                    <div>
                        {
                            appear &&
                            <div style={{position: "relative", left: 100}}>
                                <ReactEmojiEditor ref={emotor} width={500}
                                                  onChange={(content) => contentOnChange(content)}
                                                  placeholder='请遵守互联网法律和规范进行发言'/>
                                <div style={{paddingTop: 15, position: 'relative', left: 300}}>
                                    <Button style={{marginRight: 15}} type="primary" onClick={clean}>清空</Button>
                                    <Button type="primary" onClick={publishComment}>回复</Button>
                                </div>
                            </div>
                        }
                    </div>
                </div>
                {
                    comment.children && (
                        <div className={classes.Children}>
                            {
                                comment.children.map((comment) => (
                                    <Comment key={comment.id} users={users} comment={comment} level={level + 1}/>
                                ))
                            }
                        </div>
                    )
                }
            </div>
        </div>
    );
};

export default Comment;